package com.visionet.school.app.web.service.dynamic;

import com.visionet.school.app.web.common.utilities.props.PropsKeys;
import com.visionet.school.app.web.common.utilities.props.PropsUtil;
import com.visionet.school.app.web.common.utils.PageUtils;
import com.visionet.school.app.web.common.web.WebContextFactory;
import com.visionet.school.app.web.entity.dynamic.Dynamic;
import com.visionet.school.app.web.entity.dynamic.DynamicContent;
import com.visionet.school.app.web.entity.dynamic.DynamicLikes;
import com.visionet.school.app.web.entity.dynamic.vo.DynamicVo;
import com.visionet.school.app.web.entity.enums.MemberType;
import com.visionet.school.app.web.entity.file.FileClass;
import com.visionet.school.app.web.entity.file.vo.FileVo;
import com.visionet.school.app.web.entity.member.MemberFile;
import com.visionet.school.app.web.entity.vo.LoginAccountVo;
import com.visionet.school.app.web.entity.vo.StudentVo;
import com.visionet.school.app.web.repository.dynamic.DynamicContentRepository;
import com.visionet.school.app.web.repository.dynamic.DynamicLikesRepository;
import com.visionet.school.app.web.repository.dynamic.DynamicRepository;
import com.visionet.school.app.web.repository.member.MemberFileRepository;
import com.visionet.school.app.web.repository.tclass.SchoolClassRepository;
import com.visionet.school.app.web.service.file.FileClassService;
import com.visionet.school.app.web.task.DynamicImgTask;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * Created by hxpeng on 2017/4/21.
 */

@Service
public class DynamicService {

    private static final Logger logger = LoggerFactory.getLogger(DynamicService.class);

    @Resource
    private DynamicRepository dynamicRepository;

    @Resource
    private DynamicContentRepository dynamicContentRepository;

    @Resource
    private FileClassService fileClassService;

    @Resource
    private SchoolClassRepository schoolClassRepository;

    @Resource
    private MemberFileRepository memberFileRepository;

    @Resource
    private DynamicLikesRepository dynamicLikesRepository;

    public void save(DynamicVo dynamicVo){
        try {
            LoginAccountVo loginAccountVo = WebContextFactory.getWebContext().getLoginAccountVo();

            DynamicContent dynamicContent = new DynamicContent();
            dynamicContent.setContent(dynamicVo.getContent());
            dynamicContent.setIsDeleted("0");
            dynamicContentRepository.save(dynamicContent);

            if(loginAccountVo.getMemberType().equals(MemberType.PARENT.toKey())){
                List<StudentVo> studentVoList = loginAccountVo.getStudentVoList();
                if(studentVoList != null){
                    List<String> classIds = new ArrayList<>();
                    for(String s : dynamicVo.getClassIds()){
                        //一个班级只插入一条动态数据
                        if(!classIds.contains(s)){
                            StringBuffer stringBuffer = new StringBuffer("");
                            for(StudentVo studentVo : studentVoList){
                                if(StringUtils.isNotBlank(studentVo.getClassId()) || studentVo.getClassId().equals(s)){
                                    stringBuffer.append(s).append(",");
                                }
                            }
                            String studentName = stringBuffer.toString();
                            if(StringUtils.isNotBlank(studentName)){
                                studentName = studentName.substring(0,studentName.length()-1);
                                Dynamic dynamic = new Dynamic();
                                BeanUtils.copyProperties(dynamicVo,dynamic);
                                dynamic.setMemberId(loginAccountVo.getMemberId());
                                dynamic.setStudentName(studentName);
                                dynamic.setMemberName(loginAccountVo.getMemberName());
                                dynamic.setMemberType(loginAccountVo.getMemberParentGender());
                                dynamic.setMemberAvatarPath(loginAccountVo.getMemberAvatarPath());
                                dynamic.setClassId(s);
                                dynamic.setIsDeleted("0");
                                dynamic.setLikes(0);
                                dynamic.setComments(0);
                                dynamic.setDynamicContentId(dynamicContent.getId());
                                dynamicRepository.save(dynamic);
                                classIds.add(s);
                            }
                        }
                    }
                }
            }else if(loginAccountVo.getMemberType().equals(MemberType.TEACHER.toKey())){
                Dynamic dynamic = new Dynamic();
                BeanUtils.copyProperties(dynamicVo,dynamic);
                dynamic.setMemberId(loginAccountVo.getMemberId());
                dynamic.setStudentName(null);
                dynamic.setMemberName(loginAccountVo.getMemberName());
                dynamic.setMemberType(null);
                dynamic.setMemberAvatarPath(loginAccountVo.getMemberAvatarPath());
                dynamic.setClassId(dynamicVo.getClassIds().get(0));
                dynamic.setIsDeleted("0");
                dynamic.setLikes(0);
                dynamic.setComments(0);
                dynamic.setDynamicContentId(dynamicContent.getId());
                dynamicRepository.save(dynamic);
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    //根据班级ID查询动态列表
    public Map<String, Object> dynamicVoList(DynamicVo dynamicVo){
        Page<DynamicVo> objPage = dynamicRepository.findPage(dynamicVo);
        return PageUtils.getPageMap(objPage);
    }

    /**
     * 点赞动态（暂只更新点赞数，不保存点赞人）
     * @param dynamicId
     */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void likeDynamic(String dynamicId){
        Dynamic dynamic = dynamicRepository.findOne(dynamicId);
        if(dynamic != null){
            dynamic.setLikes(dynamic.getLikes() + 1);
            dynamicRepository.save(dynamic);
            LoginAccountVo loginAccountVo = WebContextFactory.getWebContext().getLoginAccountVo();

            DynamicLikes dynamicLikes = dynamicLikesRepository.hadLikes(dynamic.getId(),loginAccountVo.getMemberId());
            if(dynamicLikes == null){
                dynamicLikes = new DynamicLikes();
                dynamicLikes.setDynamicId(dynamic.getId());
                dynamicLikes.setMemberId(loginAccountVo.getMemberId());
                dynamicLikes.setMemberName(loginAccountVo.getMemberName());
                dynamicLikes.setMemberAvatarPath(loginAccountVo.getMemberAvatarPath());
                dynamicLikes.setIsDeleted("0");
                dynamicLikesRepository.save(dynamicLikes);
            }
        }
    }

    public List<FileVo> downLoadWechatImg(List<String> serverIds, String memberId){
        //设置线程池，最多九个
        try {
            List<FileVo> resultList = new ArrayList<>();
            List<Future<FileClass>> tasks = new ArrayList();
            ExecutorService executor = Executors.newFixedThreadPool(9);

            StringBuffer stringBuffer = new StringBuffer(PropsUtil.getProperty(PropsKeys.SERVER_IMG_PATH));
            stringBuffer.append("/").append(memberId);
            stringBuffer.append("_").append(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

            for(String s : serverIds){
                DynamicImgTask dynamicImgTask = new DynamicImgTask(s,stringBuffer.toString(),true);
                tasks.add(executor.submit(dynamicImgTask));
            }
            executor.shutdown();
            logger.info("===================================================");
            //当前线程阻塞，直到所有已提交的任务（包括正在跑的和队列中等待的）执行完或者等超时时间到
            //或者线程被中断，抛出InterruptedException
            executor.awaitTermination(1, TimeUnit.SECONDS);
            //获取所有的callable的返回结果，保存
            for (Future<FileClass> f : tasks) {
                FileClass fileClass = f.get();
                if(fileClass != null){
                    fileClass = fileClassService.save(fileClass);
                    MemberFile memberFile = new MemberFile();
                    memberFile.setMemberId(memberId);
                    memberFile.setFileId(fileClass.getId());
                    memberFile.setIsDeleted("0");
                    memberFileRepository.save(memberFile);

                    //返回图片路径+media_Id,mediaId用来区分
                    FileVo fileVo = new FileVo();
                    fileVo.setFilePath(fileClass.getFilePath());
                    fileVo.setThumbnail(fileClass.getThumbnail());
                    fileVo.setMediaId(fileClass.getMediaId());
                    resultList.add(fileVo);
                }
            }
            logger.info("批量文件下载完毕！！！");
            return resultList;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("图片下载失败！");
        }
    }

    public DynamicVo findDynamicInfo(String id){
        Dynamic dynamic = dynamicRepository.findOne(id);
        LoginAccountVo loginAccountVo = WebContextFactory.getWebContext().getLoginAccountVo();
        String currentMemberId = loginAccountVo.getMemberId();
        if(dynamic.getIsDeleted().equals("1")){
            return null;
        }
        if(dynamic != null){
            DynamicVo dynamicVo = new DynamicVo();
            BeanUtils.copyProperties (dynamic,dynamicVo);
            if(StringUtils.isNotBlank(dynamic.getDynamicContentId())){
                DynamicContent dynamicContent = dynamicContentRepository.findOne(dynamic.getDynamicContentId());
                if(dynamicContent != null){
                    dynamicVo.setContent(dynamicContent.getContent());
                }else{
                    dynamicVo.setContent("<p style='text-align: center;'>无内容</p>");
                }
                DynamicLikes dynamicLikes = dynamicLikesRepository.hadLikes(dynamic.getId(),currentMemberId);
                if(dynamicLikes != null){
                    dynamicVo.setHadLikes(true);
                }else{
                    dynamicVo.setHadLikes(false);
                }
                return dynamicVo;
            }
        }
        return null;
    }


}
